package com.haoxin.ai_course.modules.course.biz;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.haoxin.ai_course.common.utils.ClientSignUtils;
import com.haoxin.ai_course.common.utils.HttpJsonResult;
import com.haoxin.ai_course.common.utils.HttpUtil;
import com.haoxin.ai_course.common.utils.R;
import com.haoxin.ai_course.config.WxMaConfiguration;
import com.haoxin.ai_course.modules.apkversion.entity.LoginInfo;
import com.haoxin.ai_course.modules.course.entity.AcDialogueTopic;
import com.haoxin.ai_course.modules.course.entity.AcStatisticsAnswer;
import com.haoxin.ai_course.modules.course.entity.AcStatisticsUser;
import com.haoxin.ai_course.modules.course.entity.AcTopicAnswerResult;
import com.haoxin.ai_course.modules.course.entity.PO.AcTopicAnswerResultPO;
import com.haoxin.ai_course.modules.course.entity.PO.DecipherPO;
import com.haoxin.ai_course.modules.course.entity.PO.SysUserPO;
import com.haoxin.ai_course.modules.course.entity.VO.AcTopicAnswerResultVO;
import com.haoxin.ai_course.modules.course.entity.VO.PayStatusVO;
import com.haoxin.ai_course.modules.course.entity.VO.SysUserVO;
import com.haoxin.ai_course.modules.course.service.AcStatisticsAnswerService;
import com.haoxin.ai_course.modules.course.service.AcStatisticsUserService;
import com.haoxin.ai_course.modules.course.service.AcTopicAnswerResultService;
import com.haoxin.ai_course.modules.sys.entity.SysUser;
import com.haoxin.ai_course.modules.sys.service.SysUserService;
import com.haoxin.ai_course.modules.sys.service.SysUserTokenService;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;

/**
 * 答题结果表
 * 
 * @author xingxiangguo
 * @email bugcn@qq.com
 * @date 2022-06-06 09:44:49
 */
@Slf4j
@Component
public class AcTopicAnswerResultBusiness {
	@Autowired
	private MapperFacade mapperFacade;
	@Autowired
	AcTopicAnswerResultService acTopicAnswerResultService;
	@Autowired
	AcStatisticsAnswerService acStatisticsAnswerService;
	@Autowired
	AcStatisticsUserService acStatisticsUserService;
	public HttpJsonResult<AcTopicAnswerResultVO> save(@RequestBody AcTopicAnswerResultPO acTopicAnswerResultPO,Long userId) {
		HttpJsonResult<AcTopicAnswerResultVO> result = new HttpJsonResult<AcTopicAnswerResultVO>();
		QueryWrapper<AcDialogueTopic> acDialogueTopicQueryWrapper = new QueryWrapper<AcDialogueTopic>();
		acDialogueTopicQueryWrapper.lambda().eq(AcDialogueTopic::getTopicCode, acTopicAnswerResultPO.getTopicCode());
		Integer topicId = acTopicAnswerResultPO.getTopicId();
		QueryWrapper<AcStatisticsUser> acStatisticsUserQueryWrapper = new QueryWrapper<AcStatisticsUser>();
		acStatisticsUserQueryWrapper.lambda().eq(AcStatisticsUser::getUserId, userId);
		acStatisticsUserQueryWrapper.lambda().eq(AcStatisticsUser::getCourseId, acTopicAnswerResultPO.getCourseId());
		acStatisticsUserQueryWrapper.lambda().eq(AcStatisticsUser::getCourseFinish, 0);
		AcStatisticsUser acStatisticsUser = acStatisticsUserService.getOne(acStatisticsUserQueryWrapper);
//		获取已答题目的答案
		String itemRecord = acStatisticsUser.getItemRecord();
		JSONObject  itemRecordJson = new JSONObject();
		if(StringUtils.isNotBlank(acStatisticsUser.getItemRecordJson())) {
			itemRecordJson = JSONObject.parseObject(acStatisticsUser.getItemRecordJson());
		}
//		拼接当前答案
		if(StringUtils.isBlank(itemRecord)) {
			itemRecord = acTopicAnswerResultPO.getAnswerCode();
			itemRecordJson = new JSONObject();
			itemRecordJson.put(""+topicId, acTopicAnswerResultPO);
		}else {
//			处理重复数据
			if(itemRecordJson.get(""+topicId) != null) {
				result.setCode(200);
				return result;
			}
			itemRecord += ","+acTopicAnswerResultPO.getAnswerCode();
			itemRecordJson.put(""+topicId, acTopicAnswerResultPO);
		}
		acStatisticsUser.setItemRecordJson(itemRecordJson.toJSONString());
		acStatisticsUser.setItemRecord(itemRecord);
//		入库
		boolean updateResult =acStatisticsUserService.updateById(acStatisticsUser);
		log.info("答题结果保存完毕，入库是否成功：{},答题结果：{}",updateResult,acStatisticsUser);
//		找到未完课的数据记录
		QueryWrapper<AcTopicAnswerResult> qw0 = new QueryWrapper<AcTopicAnswerResult>();
		qw0.lambda().eq(AcTopicAnswerResult::getUserId, userId);
		qw0.lambda().eq(AcTopicAnswerResult::getCourseId, acTopicAnswerResultPO.getCourseId());
		qw0.lambda().eq(AcTopicAnswerResult::getTopicId, topicId);
		qw0.lambda().eq(AcTopicAnswerResult::getAnswerId, acTopicAnswerResultPO.getId());
		AcTopicAnswerResult acTopicAnswerResult = acTopicAnswerResultService.getOne(qw0);
//		如果不存在，答题结果入库,只在第一次学习时记录
		if (acTopicAnswerResult == null&& acStatisticsUser.getRevisitTimes() == 0 ) {
			log.info("保存并统计答题情况，已答题记录：{}",acTopicAnswerResult);
			acTopicAnswerResult = mapperFacade.map(acTopicAnswerResultPO, AcTopicAnswerResult.class);
			acTopicAnswerResult.setAnswerId(acTopicAnswerResultPO.getId());
			acTopicAnswerResult.setUserId(userId);
			acTopicAnswerResult.setTopicId(topicId);
			acTopicAnswerResult.setRevisitTimes(acStatisticsUser.getRevisitTimes());
			acTopicAnswerResultService.save(acTopicAnswerResult);
//	        统计当前题目当前结果回答情况
//	        统计选中数量，统计选中人数，记录题目名称
//	        从回答结果表统计 选中人数 和 选中占比
			List<AcStatisticsAnswer> acStatisticsAnswerList = acStatisticsAnswerService
					.countSelectRateAndSelectedCount(acTopicAnswerResultPO.getCourseId(), topicId);
			QueryWrapper<AcStatisticsAnswer> qw = new QueryWrapper<AcStatisticsAnswer>();
			qw.lambda().eq(AcStatisticsAnswer::getCourseId, acTopicAnswerResultPO.getCourseId());
			qw.lambda().eq(AcStatisticsAnswer::getTopicId, topicId);
			boolean deleteCount = acStatisticsAnswerService.remove(qw);
			log.info("删除结果===========：" + deleteCount);
			acStatisticsAnswerService.saveBatch(acStatisticsAnswerList);
			log.info("保存答题并统计结果完成");
		}
		result.setCode(200);
		return result;
	}
}
